#include "TextureManager.h"

#include <SDL.h>
#include <SDL_image.h>

#ifdef DEBUG_NEW
#include "debug/debug_new.h"
#endif
TextureManager::TextureManager() {
}

TextureManager::~TextureManager() {
    for (unordered_map<string, GLuint>::iterator it = _textures.begin();
            it != _textures.end(); ++it) {
        glDeleteTextures(1, &(it->second));
    }
}

GLuint TextureManager::get_texture(string filename, GLint filter) {
    if (!_textures[filename]) {
        SDL_Surface* surface = IMG_Load(filename.c_str());
        GLuint texture;
        glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
        SDL_PixelFormat *format = surface->format;
        if (format->Amask) {
            gluBuild2DMipmaps(GL_TEXTURE_2D, 4,
                    surface->w, surface->h, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels);
        } else {
            gluBuild2DMipmaps(GL_TEXTURE_2D, 3,
                    surface->w, surface->h, GL_RGB, GL_UNSIGNED_BYTE, surface->pixels);
        }
        SDL_FreeSurface(surface);
        _textures[filename] = texture;
        return texture;

    } else {
        return _textures[filename];
    }
}
